using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using RAG.Application.Dtos;
using RAG.Application.Interfaces;
using RAG.Application.Commands;
using RAG.Domain.Interfaces;
using System.Security.Claims;
using Microsoft.AspNetCore.Http;

namespace RAG.Api.Controllers;

[ApiController]
[Route("api/[controller]")]
[Authorize] // 恢复JWT认证
public class UsersController : ControllerBase
{
    private readonly IAppUserService _userService;
    private readonly IAppAvatarService _avatarService;
    private readonly IDomainEventPublisher _eventPublisher;

    public UsersController(
        IAppUserService userService,
        IAppAvatarService avatarService,
        IDomainEventPublisher eventPublisher)
    {
        _userService = userService;
        _avatarService = avatarService;
        _eventPublisher = eventPublisher;
    }

    /// <summary>
    /// 获取用户列表
    /// </summary>
    [HttpGet]
    public async Task<IActionResult> GetUsers([FromQuery] int page = 1, [FromQuery] int size = 10, [FromQuery] string? search = null)
    {
        var result = await _userService.GetUsersAsync(page, size, search);
        return Ok(result);
    }

    /// <summary>
    /// 获取头像文件（静态路由，放在参数路由之前）
    /// </summary>
    [HttpGet("avatar-file/{fileName}")]
    [AllowAnonymous] // 头像文件可以匿名访问
    public async Task<IActionResult> GetAvatarFile(string fileName)
    {
        var (fileBytes, contentType, actualFileName) = await _avatarService.GetAvatarFileAsync(fileName);
        return File(fileBytes, contentType, actualFileName);
    }

    /// <summary>
    /// 获取用户详情
    /// </summary>
    [HttpGet("{userId:guid}")]
    public async Task<IActionResult> GetUser(Guid userId)
    {
        var result = await _userService.GetUserByIdAsync(userId);
        return Ok(result);
    }

    /// <summary>
    /// 获取用户角色
    /// </summary>
    [HttpGet("{userId:guid}/roles")]
    public async Task<IActionResult> GetUserRoles(Guid userId)
    {
        var result = await _userService.GetUserRolesAsync(userId);
        return Ok(result);
    }

    /// <summary>
    /// 获取用户角色信息（详细）
    /// </summary>
    [HttpGet("{userId:guid}/roles-info")]
    public async Task<IActionResult> GetUserRolesInfo(Guid userId)
    {
        var result = await _userService.GetUserRolesInfoAsync(userId);
        return Ok(result);
    }

    /// <summary>
    /// 获取用户头像信息
    /// </summary>
    [HttpGet("{userId:guid}/avatar-info")]
    public async Task<IActionResult> GetUserAvatarInfo(Guid userId)
    {
        var result = await _avatarService.GetUserAvatarInfoAsync(userId);
        return Ok(result);
    }

    /// <summary>
    /// 创建用户
    /// </summary>
    [HttpPost]
    [AllowAnonymous] // 创建用户不需要Token验证
    public async Task<IActionResult> CreateUser([FromBody] CreateUserDto dto)
    {
        var result = await _userService.CreateUserAsync(dto);
        return Ok(result);
    }

    /// <summary>
    /// 更新用户
    /// </summary>
    [HttpPut("{userId:guid}")]
    public async Task<IActionResult> UpdateUser(Guid userId, [FromBody] UpdateUserDto dto)
    {
        var result = await _userService.UpdateUserAsync(userId, dto);
        return Ok(result);
    }

    /// <summary>
    /// 删除用户
    /// </summary>
    [HttpDelete("{userId:guid}")]
    public async Task<IActionResult> DeleteUser(Guid userId)
    {
        var currentUserId = GetCurrentUserId();
        var result = await _userService.DeleteUserAsync(userId, currentUserId);
        return Ok(result);
    }

    /// <summary>
    /// 修改密码
    /// </summary>
    [HttpPost("{userId:guid}/change-password")]
    public async Task<IActionResult> ChangePassword(Guid userId, [FromBody] ChangePasswordDto dto)
    {
        try
        {
            Console.WriteLine($"收到修改密码请求 - UserId: {userId}");
            var currentUserId = GetCurrentUserId();
            var result = await _userService.ChangePasswordAsync(userId, dto, currentUserId);
            return Ok(result);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"修改密码控制器异常: {ex.Message}");
            return BadRequest(new { Error = ex.Message });
        }
    }

    /// <summary>
    /// 启用用户
    /// </summary>
    [HttpPost("{userId:guid}/enable")]
    public async Task<IActionResult> EnableUser(Guid userId)
    {
        var currentUserId = GetCurrentUserId();
        var result = await _userService.EnableUserAsync(userId, currentUserId);
        return Ok(result);
    }

    /// <summary>
    /// 禁用用户
    /// </summary>
    [HttpPost("{userId:guid}/disable")]
    public async Task<IActionResult> DisableUser(Guid userId)
    {
        var currentUserId = GetCurrentUserId();
        var result = await _userService.DisableUserAsync(userId, currentUserId);
        return Ok(result);
    }

    /// <summary>
    /// 分配角色
    /// </summary>
    [HttpPost("{userId:guid}/roles")]
    public async Task<IActionResult> AssignRoles(Guid userId, [FromBody] AssignRolesDto dto)
    {
        var currentUserId = GetCurrentUserId();
        var result = await _userService.AssignRolesAsync(userId, dto, currentUserId);
        return Ok(result);
    }

    /// <summary>
    /// 上传用户头像
    /// </summary>
    [HttpPost("{userId:guid}/avatar")]
    public async Task<IActionResult> UploadUserAvatar(Guid userId, IFormFile file)
    {
        var currentUserId = GetCurrentUserId();
        var result = await _avatarService.UploadUserAvatarAsync(userId, file, currentUserId);
        return Ok(result);
    }



    /// <summary>
    /// 获取当前用户ID
    /// </summary>
    private Guid GetCurrentUserId()
    {
        var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier);
        if (userIdClaim != null && Guid.TryParse(userIdClaim.Value, out var userId))
        {
            return userId;
        }
        return Guid.Empty;
    }
} 